package com.tanhua.dubbo.api.mongo;

import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 今日佳人服务接口实现类
 */
@DubboService
public class RecommendUserApiImpl implements RecommendUserApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 今日佳人
     * 根据当前用户id作为toUserId条件查询
     * score进行降序排序
     * 只查询一条记录
     * @param userId
     * @return
     */
    @Override
    public RecommendUser queryWithMaxScore(Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("toUserId").is(userId));//根据当前用户id作为toUserId条件查询
        query.with(Sort.by(Sort.Direction.DESC,"score"));//score进行降序排序
        return mongoTemplate.findOne(query,RecommendUser.class);//查询一条记录
    }

    /**
     * 分页查询推荐用户列表
     *
     * @param page
     * @param pageSize
     * @param userId
     * @return
     */
    @Override
    public PageResult<RecommendUser> findPageRecommendUser(Long page, Long pageSize, Long userId) {
        //1查询总记录数
        Query query = new Query();
        long counts = mongoTemplate.count(query, RecommendUser.class);
        //2当前页面数据
        query.limit(pageSize.intValue()).skip((page-1)*pageSize);
        //2.1 date降序
        query.with(Sort.by(Sort.Direction.DESC,"date"));
        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);
        //3返回PageResult
        return new PageResult<>(page,pageSize,counts,recommendUserList);
    }

    /**
     * 根据personUserId和当前用户id查询推荐表获取获取缘分值
     *
     * @param userId
     * @param personUserId
     * @return
     */
    @Override
    public RecommendUser findByUserId(Long userId, Long personUserId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(personUserId).and("toUserId").is(userId));
        return mongoTemplate.findOne(query,RecommendUser.class);
    }

    /**
     * 探花推荐列表查询
     *
     * @param currentUserId
     */
    @Override
    public List<RecommendUser> cards(Long currentUserId) {
        //1.查询user_like喜欢 不喜欢数据查询
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(currentUserId));
        List<UserLike> userLikes = mongoTemplate.find(query, UserLike.class);
        //1.1获取所有喜欢和不喜欢的用户ids
        List<Long> likeUserIds = new ArrayList<>();
        if(!CollectionUtils.isEmpty(likeUserIds)) {
            likeUserIds = userLikes.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
        }
        //2.基于第一步数据进行过滤 + toUserId=当前用户id 随机查询
        Criteria userIds = Criteria.where("toUserId").is(currentUserId).and("userId").nin(likeUserIds);
        //参数1：构造条件对象 参数2：userIds条件对象 匹配的用户ids( 有相同用户 排除用户ids) 参数3：随机条件
        TypedAggregation<RecommendUser> recommendUserTypedAggregation =
                TypedAggregation.newAggregation(RecommendUser.class, Aggregation.match(userIds),Aggregation.sample(10));
        //参数1：随机的条件 参数2：随机表
        AggregationResults<RecommendUser> aggregate = mongoTemplate.aggregate(recommendUserTypedAggregation, RecommendUser.class);
        //3.返回结果
        return aggregate.getMappedResults();
    }
}
